import { Link, useNavigate } from 'react-router-dom'
import { Card, Breadcrumb, Form, Button, Radio, DatePicker, Select, Popconfirm } from 'antd'
//引入汉化包，时间选择器显示中文
import locale from 'antd/es/date-picker/locale/zh_CN'

// 数据模块-导入资源
import { Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from '@/assets/error.png'
import { useChannel } from '@/hooks/useChannel'
import { useEffect, useState } from 'react'
import { delArticleAPI, getArticleListAPI } from '@/apis/article'

import moment from 'moment';

const { Option } = Select
const { RangePicker } = DatePicker

const Article = () => {
  const navigate = useNavigate()
  //获取频道列表
  const { channelList } = useChannel()
  // 准备列数据
  // 定义状态枚举
  const status = {
    0: <Tag color='blue'>草稿</Tag>,
    1: <Tag color='warning'>待审核</Tag>,
    2: <Tag color='success'>审核通过</Tag>,
    3: <Tag color='red'>审核失败</Tag>

  }



  const columns = [
    {
      title: '封面',
      dataIndex: 'artImages',
      width: 120,
      render: artImages => {
        //注意这里artImages不能为null，必须是"",才能取值（有问题时检查数据库的脏数据）
        return <img src={artImages.split(',')[0] || img404} width={80} height={60} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'artTitle',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => status[data]
    },
    {
      title: '发布时间',
      //dataIndex: 'artCreate'
      render: artCreate => {
        return moment(artCreate).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      title: '阅读数',
      dataIndex: 'readCount'
    },
    {
      title: '评论数',
      dataIndex: 'commentCount'
    },
    {
      title: '点赞数',
      dataIndex: 'likeCount'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => navigate(`/publish?id=${data.artId}`)}
            />
            <Popconfirm
              title="确认删除该条文章吗?"
              onConfirm={() => delArticle(data)}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  // 准备表格body数据
  // const data = [
  //   {
  //     id: '8218',
  //     comment_count: 0,
  //     cover: {
  //       images: [],
  //     },
  //     like_count: 0,
  //     pubdate: '2019-03-11 09:00:00',
  //     read_count: 2,
  //     status: 2,
  //     title: 'wkwebview离线化加载h5资源解决方案'
  //   }
  // ]

  //筛选功能
  //1.准备参数
  const [reqData, setReqData] = useState({
    status: '',
    channelId: '',
    minDate: '',
    maxDate: '',
    //当前页数
    pageStart: 1,
    //分页条数
    limit: 5
  })
  //获取文章列表
  const [list, setList] = useState([])
  const [count, setCount] = useState([])
  useEffect(() => {
    async function getList() {
      const res = await getArticleListAPI(reqData)
      setList(res.data.results)
      setCount(res.data.count)
    }
    getList()
  }, [reqData])//[变化数据依赖项]

  //2.获取筛选数据
  const onFinish = (formValue) => {
    console.log(formValue)
    //3.把表单数据传递到参数中
    setReqData({
      ...reqData,
      status: formValue.status,
      channelId: formValue.channel_id,
      minDate: formValue.date ? formValue.date[0].format('YYYY-MM-DD') : '',
      maxDate: formValue.date ? formValue.date[1].format('YYYY-MM-DD') : ''
    })
    //4.formValue数据发生变化就重新拉取文章列表，带条件渲染table（重复的--在useEffect中添加变化依赖项即可）
  }

  //分页
  const onPageChange = (page) => {
    console.log(page)
    //修改筛选条件参数依赖刷新列表
    setReqData({
      ...reqData,
      pageStart: page
    })
  }

  //删除
  const delArticle = async (data) => {
    console.log('删除被点击了', data)
    await delArticleAPI(data.artId)
    //更新列表，不改数据刷新当前页
    setReqData({
      ...reqData
    })
    //更新data列表并设置重新分页
    // setReqData({
    //   pageStart: 1,
    //   limit: 10
    // })

  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: '文章列表' },
          ]} />
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: '' }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={''}>全部</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Select
              placeholder="请选择文章频道"
              defaultValue="默认选项"
              style={{ width: 120 }}
            >
              {channelList?.map(item => <Option key={item.channelsId} value={item.channelsId}>{item.channelsName}</Option>)}
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/*表格区域*/}
      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        <Table rowKey="id" columns={columns} dataSource={list} pagination={{
          total: count,
          pageSize: reqData.limit,
          onChange: onPageChange
        }} />
      </Card>
    </div>
  )
}

export default Article